package cxm.proj.xtalk.smack;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.jivesoftware.smack.RosterGroup;

import cxm.lib.util.MyLog;

public class GroupManager {
	private static GroupManager instance = null;
	private static final String publicGroupName = "XtalkGroup";
	private static final int retryCount = 20;
	
	private GroupManager() {
		
	}
	
	public static GroupManager getInstance() {
		if (null == instance)
			instance = new GroupManager();
		
		return instance;
	}
	
	private List<RosterGroup> getGroupsSingle() {
        List<RosterGroup> grouplist = new ArrayList<RosterGroup>();
        
        Collection<RosterGroup> rosterGroup = ConnectManager.getInstance().getConnector().
        		getConnection().getRoster().getGroups();
        Iterator<RosterGroup> i = rosterGroup.iterator();
        while (i.hasNext())
            grouplist.add(i.next());
        
        MyLog.Log(MyLog.Level.Debug, "Get group count " + grouplist.size());
        return grouplist;
	}
	
	private List<RosterGroup> getGroupsRetry() {
		List<RosterGroup> grouplist = null;
		for (int i = 0; i < retryCount; i++) {
			grouplist = this.getGroupsSingle();
			if (grouplist.size() > 0)
				break;
			else
				MyLog.Log(MyLog.Level.Warning, "Get groups null, retry at " + i);
		}
		
		return grouplist;
	}
	
	// this may fail some times
	public List<RosterGroup> getGroups() {
		return this.getGroupsRetry();
    }
	
	public Group getGroupByName(String name) {
		List<RosterGroup> groups = this.getGroupsRetry();
		
		for (RosterGroup item : groups)
			if (item.getName().equals(name))
				return new Group(name);
		
		return null;
	}
	
	public Group getPublicGroup() {
		return this.getGroupByName(publicGroupName);
	}
}
